package com.java202411.repository;


import com.java202411.entity.UserEntity;
import com.java202411.repository.client.RoleDatabaseClient;
import com.java202411.repository.client.UserDatabaseClient;
import com.java202411.repository.client.UserRoleDatabaseClient;
import com.java202411.repository.table.RoleTable;
import com.java202411.repository.table.UserRoleTable;
import com.java202411.repository.table.UserTable;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;

@Repository
@RequiredArgsConstructor

public class UserRepository {
    private final UserDatabaseClient userDatabaseClient;
    private final RoleDatabaseClient roleDatabaseClient;
    private final UserRoleDatabaseClient userRoleDatabaseClient;

    public Optional<UserEntity> findByEmail(String email) {
        if (StringUtils.isBlank(email)) {
            return Optional.empty();
        }

        Optional<UserTable> userRow = userDatabaseClient.findByEmail(email);
        Optional<UserEntity> user = userRow.map(
                it -> UserEntity.builder()
                        .id(it.getId())
                        .email(it.getEmail())
                        .password(it.getPassword())
                        .createdAt(it.getCreatedAt())
                        .updatedAt(it.getUpdatedAt())
                        .build()
        );
        if (user.isPresent()) {
            Long userId = user.get().getId();

            List<UserRoleTable> userRoles = userRoleDatabaseClient.findAllByUserId(userId);
            Iterable<RoleTable> roles = roleDatabaseClient.findAllById(
                    userRoles.stream().map(UserRoleTable::getUserId).toList()
            );

            user.get().setRoles(
                    StreamSupport.stream(roles.spliterator(), false)
                            .map(RoleTable::getCode)
                            .toList()
            );
        }

        return user;
    }

    public UserEntity save(UserEntity user) {

        UserTable row = UserTable.builder()
                .id(user.getId())
                .createdAt(user.getCreatedAt())
                .updatedAt(user.getUpdatedAt())
                .email(user.getEmail())
                .password(user.getPassword())
                .build();

        row = userDatabaseClient.save(row);

        return UserEntity.builder()
                .id(row.getId())
                .createdAt(row.getCreatedAt())
                .updatedAt(row.getUpdatedAt())
                .email(row.getEmail())
                .password(row.getPassword())
                .build();
    }
}

